import { Context } from 'egg';
import { JsonWebTokenError, TokenExpiredError } from 'jsonwebtoken';
import { Result } from '../../Result';
import { getIdFromToken } from '../../util/JwtUtil';

module.exports = option => {
  return async function jwt(ctx: Context, next) {
    const { authorization } = ctx.request.header;
    if (!authorization) {
      ctx.body = Result.error(500, '请先登录');
      return;
    }
    try {
      getIdFromToken(authorization, option.secret);
    } catch (error) {
      if (error instanceof JsonWebTokenError || SyntaxError) {
        ctx.body = Result.error(500, 'token错误');
      }
      if (error instanceof TokenExpiredError) {
        ctx.body = Result.error(500, '认证信息已过期,请重新登录');
      }
      console.log(error);
      return;
    }

    await next();
  };
};
